package com.bluesky.jwf.component.tree;

import java.io.Serializable;
import java.util.List;

/**
 * caution: tend to avoid using it.
 * 
 * @author hz00260
 * 
 */
public abstract class TreeNodeNavigator implements Serializable {
	public abstract Object getParent(Object self);

	public abstract List getChildren(Object self);

	public boolean isLastChild(Object node) {
		Object parent = getParent(node);
		if (parent == null)
			return true;

		List children = getChildren(parent);
		if (children.get(children.size() - 1) == node)
			return true;
		else
			return false;

	}

	/**
	 * get the ancestor, ie. depth=1, ancestor is its parent, depth=2 means its
	 * grandparent.
	 * 
	 * @param ng
	 * @param node
	 * @param depth
	 * @return
	 */
	public Object getAncester(Object node, int depth) {
		Object a = node;
		for (int i = 0; i < depth; i++)
			a = getParent(a);

		return a;
	}

	public int getDepth(Object node) {
		int depth = 0;
		Object p = getParent(node);
		while (p != null) {
			p = getParent(p);
			depth++;
		}
		return depth;
	}

	public boolean isAncestor(Object self, Object ancestor) {
		Object p = getParent(self);
		while (p != null) {
			if (p == ancestor)
				return true;

			p = getParent(p);
		}
		return false;
	}

	public interface Tranverser {
		void process(Object obj);
	}

	public void tranverse(Object obj, Tranverser t) {
		t.process(obj);
		List list = getChildren(obj);
		for (Object o : list)
			tranverse(o, t);

	}
}
